package com.cy.pj.goods.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;

    // 初始化一个日志对象
    private static final Logger log =
            LoggerFactory.getLogger(DefaultGoodsDao.class);// 在哪个类创建日志对象，就写哪个类的字节码对象

    Map<String, Object> rowMap(ResultSetMetaData rsmd, ResultSet rs) throws SQLException {
        Map<String, Object> map = new HashMap<>();
        for(int i = 1; i <= rsmd.getColumnCount(); i++) {
            map.put(rsmd.getColumnName(i), rs.getObject(i));
        }
        return map;
    }

    public void close(ResultSet rs, Statement stat, Connection conn) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }
        if(stat != null) {
            try {
                stat.close();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e3) {
                e3.printStackTrace();
            }
        }
    }

    @Override
    public List<Map<String, Object>> findGoods(){
        List<Map<String,Object>> list = new ArrayList<>();
        Connection conn = null;
        Statement statement = null;
        String sql = "  select * from tb_goods";
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            statement = conn.createStatement();
            rs = statement.executeQuery(sql);
            ResultSetMetaData rsmd = rs.getMetaData();

            while(rs.next()) {
                //Map<String, Object> map = new HashMap<String, Object>();
                //map.put("id", rs.getInt("id"));
                //map.put("name", rs.getString("name"));
                //map.put("remark", rs.getString("remark"));
                //map.put("createdTime", rs.getTimestamp("createdTime"));
                //list.add(map);

                list.add(rowMap(rsmd, rs));
            }
            return list;
        } catch (SQLException throwables) {
            //throwables.printStackTrace();
            log.info("查询异常，{}", throwables.getMessage()); // {}表示占位符
            // 一般记录错误用error
            log.error("查询异常222，{}", throwables.getMessage()); // {}表示占位符
            //return null;
            throw new RuntimeException("数据查询失败：" + throwables.getMessage());
        } finally {
            if(rs != null) {
                try {
                    rs.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(statement != null) {
                try {
                    statement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }
    }
}

/**
 * 优点：
 * 1)代码简单 步骤固定
 * 2)使用了连接池，优化了建立连接的过程，从池中获取连接，提高了数据访问性能
 * 3)使用了Map做映射，简化了pojo对象定义
 *
 * 缺点：
 * 1)可重用性比较差
 * 2)行映射不够灵活
 * 3)异常的处理
 * 4)Map封装数据，值不可控(建议使用pojo对象)
 * 5)对共性代码没有封装
 */
